#!/usr/bin/env python3

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


import portage
from datetime import datetime
from .._handy import ElementMapType1
from .._datasrc import DataSourceBase


class DataSource(DataSourceBase):

    def __init__(self, tmpDir):
        self._tmpDir = tmpDir

    @property
    def name(self):
        return "gentoo-linux"

    @property
    def description(self):
        return "Installed element on Gentoo Linux"

    @property
    def homepage(self):
        return ""

    @property
    def supported_etypes(self):
        return ["game"]

    @property
    def supported_dir_types(self):
        return ["system", "user"]

    def get_priority(self, etype):
        return 9000

    def map_element(self, etype, esource, eindex):
        return _idMap.map_element(esource, eindex)

    def map_element_reverse(self, etype, eindex):
        return _idMap.map_element_reverse(eindex)

    def retrieve_sync_data_last_update_time(self, etype):
        return datetime.now()

    def update_sync_data(self, etype, db_conn):
        pkgSet = set()
        for v in _idMap.values():
            for v2 in v.values():
                for pkg in v2:
                    pkgSet.add(pkg)

        with db_conn:
            db_conn.execute("DELETE FROM main.element_part WHERE esource = ?", (self.name, ))
            for pkg in pkgSet:
                if MyUtil.portageIsPkgInstalled(pkg):
                    db_conn.execute('''
                        INSERT INTO main.element_part
                            (esource, eindex, pname)
                            VALUES (?, ?, ?)
                    ''', (self.name, pkg, "installed"))

    def get_element_part_url(self, etype, eindex, pname):
        return None                         # local only

    def test_element_part_url(self, etype, eindex, pname):
        assert False

    def is_element_part_cache_update_needed(self, etype, eindex, pname):
        return False                        # update through other means

    def get_element_part_cache_last_update_time(self, etype, eindex, pname):
        return None

    def get_element_part_cache_local_path(self, etype, eindex, pname):
        return "/"

    def cache_element_part(self, etype, eindex, pname, cache_time):
        # do nothing
        pass

    def uncache_element_part(self, etype, eindex, pname):
        # do nothing
        pass

    def clean(self, etype, all_cache=False):
        # do nothing
        pass


class MyUtil:

    @staticmethod
    def portageIsPkgInstalled(pkgName):
        """pkgName can be package-name or package-atom"""

        vartree = portage.db[portage.root]["vartree"]
        varCpvList = vartree.dbapi.match(pkgName)
        return len(varCpvList) != 0


_idMap = ElementMapType1({
    "steam": {
        "225260"            : ["games-action/brutal-legend-gog"],
        "26800"             : ["games-puzzle/braid-gog", "games-puzzle/braid-hb"],
        "22000"             : ["games-puzzle/world-of-goo-hb", "games-puzzle/world-of-goo-gog"],
    },
    "gog": {
        "1207659253"        : ["games-action/brutal-legend-gog"],
        "1461061433"        : ["games-puzzle/braid-gog", "games-puzzle/braid-hb"],
        "1421855536"        : ["games-puzzle/world-of-goo-hb", "games-puzzle/world-of-goo-gog"],
    },
    "igdb": {
        "brutal-legend"     : ["games-action/brutal-legend-gog"],
        "supertux"          : ["games-arcade/supertux"],
        "supertuxkart"      : ["games-action/supertuxkart"],
        "freedoom"          : ["games-fps/freedoom"],
        "braid"             : ["games-puzzle/braid-gog", "games-puzzle/braid-hb"],
        "world-of-goo"      : ["games-puzzle/world-of-goo-hb", "games-puzzle/world-of-goo-gog"],
    }
})
